#include "imGeometry.h"
#include "imGraphics.h"

using std::ifstream;
using std::ofstream;
using std::ios;

struct SMSHeader {
	unsigned int NumVerts, NumFaces;
};

Mesh::Mesh() {
}

Mesh::Mesh(iPrimitive &Primitive) {
	Driver = NULL;
	BuildFromPrimitive(Primitive);
}

Mesh::Mesh(char* Path) {
	ifstream f(Path, ios::in | ios::binary);

	if(f.is_open())
		LoadFromFile(&f);
	f.close();
}

void Mesh::BuildFromPrimitive(iPrimitive &Primitive) {
	NumVertices = Primitive.GetNumVerts();
	NumFaces = Primitive.GetNumFaces();

	Vertices = new Vertex[NumVertices];
	if(NumVertices < 65536) {
		Indices = new unsigned short[NumFaces * 3];
		IndexSize = sizeof(short) * NumFaces * 3;
	} else {
		Indicesl = new unsigned long[NumFaces * 3];
		IndexSize = sizeof(long) * NumFaces * 3;
	}

	memcpy(Vertices, Primitive.GetVertices(), sizeof(Vertex) * NumVertices);
	memcpy(Indices, Primitive.GetIndices(), sizeof(WORD) * NumFaces * 3);

	HookToDriver();
}

void Mesh::LoadFromFile(ifstream* File) {
	SMSHeader Header;

	File->seekg(0, ios::end);
	int FileEnd = (int)File->tellg();
	File->seekg(0, ios::beg);

	File->read((char*)&Header, sizeof(Header));
	//File->seekg(0, ios::beg);

	NumVertices = Header.NumVerts;
	NumFaces = Header.NumFaces;
	NumIndices = Header.NumFaces * 3;

	Vertices = new Vertex[NumVertices];
	Indices = new WORD[NumIndices];

	//File->seekg(sizeof(Header), ios::beg);
	File->read((char*)Vertices, sizeof(Vertex) * NumVertices);

	//File->seekg(sizeof(Header) + (sizeof(Vertex) * NumVertices), ios::beg);
	File->read((char*)Indices, sizeof(WORD) * NumIndices);
		
	HookToDriver();

	return;
};

void Mesh::SaveToFile(ofstream* File) {
};

void Mesh::HookToDriver() {
	if(imGraphics::g_GFX == NULL) return;
	Driver = imGraphics::g_GFX->GetMeshDriver();
	Driver->Hook(&Vertices[0], NumVertices, &Indices[0], NumFaces, 2);
};

void Mesh::Predraw(void) {
	Driver->Predraw();
};

void Mesh::Draw(int Subset) {
	Driver->Draw(Subset);
};